//模拟实现pow库函数
#include <iostream>

bool g_InvalidInput = false;

// double PowerWithUnsignedExponent(double number, int abs_exponent)
// {
//     double result = number;
//     for(int i = 1; i < abs_exponent; i++)
//     {
//         result *= number;
//     }
//     return result;
// }

double PowerWithUnsignedExponent(double number, int abs_exponent)
{
    if(abs_exponent == 1)
        return number;

    double result = PowerWithUnsignedExponent(number, abs_exponent >> 1);
    result *= result;
    //处理基数次方
    if(abs_exponent & 1 == 1)
        result *= number;
    return result;
}

double Power(double number, int exponent)
{
    g_InvalidInput = false;

    //0不能做为底数
    if(number == 0.0 && exponent < 0)
    {
        throw g_InvalidInput = true;
        return 0.0;
    }

    //如果是0次方的话
    if(exponent == 0)
        return 1.0;
    if(number == 0.0)
        return 0.0;

    //先算出number的绝对值次方
    unsigned int abs_exponent = (unsigned int)exponent;
    if(exponent < 0)
        abs_exponent = (unsigned int)(-exponent);
    
    double result = PowerWithUnsignedExponent(number, abs_exponent);
    //如果是负指数，那么倒过来
    if(exponent < 0)
    {
        result = 1.0 / result;
    }
    return result;
}

int main()
{
    std::cout << Power(2.0, 4) << std::endl;
    std::cout << Power(2.0, 0) << std::endl;
    std::cout << Power(0.0, 2) << std::endl;
    std::cout << Power(2.0, -4) << std::endl;
    return 0;
}

